<?php


namespace app\admin\controller;


use app\admin\model\CustomerServiceAccount;
use app\admin\model\CustomerServiceAccountMiddle;
use app\admin\model\CustomerServiceGroup;
use app\admin\model\CustomerServicePersonnel;
use app\admin\model\GuoXueLog;
use app\admin\model\KefuUser;
use app\admin\model\Order;
use app\admin\model\User;
use app\admin\model\UserInfo;
use app\api\model\AdjustLog;
use app\common\controller\admin\Base;
use think\Db;

class Statistics extends Base
{
    public function statisticsFrom()
    {
        //设置初始返回
        $list = [];
        //已分配用户搜索条件
        $distributionUserWhere = [

        ];
        //联系客服的用户数搜索条件
        $contactUserWhere = [
            'is_check_kf_switch' => 1
        ];
        //系统支付页面数量
        $sysPayViewWhere = [
            'generate_type' => 1,
            'status' => 3
        ];
        //系统订单支付金额
        $sysOrderWhere = [
            'generate_type' => 1,
            'status' => 3
        ];
        //人工支付页面数量
        $artificialPayViewWhere = [
            'generate_type' => 2,
            'status' => 3
        ];
        //人工支付订单金额
        $artificialOrderWhere = [
            'generate_type' => 2,
            'status' => 3
        ];
        //所有账号列表
        $accountWhere = [
//            'status' => 1,
            'is_del' => 0,
//            'switch' => 1
        ];
        //所有客服列表
        $personnelWhere = [
            'is_del' => 0,
        ];
        $personnelAccountWhere = [
            'is_del' => 0,
//            'switch' => 1,
        ];
        $order = $this->request->post('order', 'total_amount');
        $sort = $this->request->post('sort', 'SORT_DESC');
        $startOpenTime = $this->request->post('start_time', date('Y-m-d', time()));
        $endOpenTime = $this->request->post('end_time', date('Y-m-d', time()));
        $serviceGroupName = $this->request->post('customer_service_group_name', '');
        $servicePersonnelName = $this->request->post('customer_service_personnel_name', '');
        $serviceAccountName = $this->request->post('customer_service_account_name', '');
        $partnerName = $this->request->post('partner_name', '');
        $appBaseId = $this->request->post('app_base_id', '');
        if ($appBaseId != '') {
            $accountWhere['app_base_id'] = $appBaseId;
            $personnelAccountWhere['app_base_id'] = $appBaseId;
            $distributionUserWhere['app_base_id'] = $appBaseId;
            $contactUserWhere['app_base_id'] = $appBaseId;
            $sysPayViewWhere['app_base_id'] = $appBaseId;
            $sysOrderWhere['app_base_id'] = $appBaseId;
            $artificialPayViewWhere['app_base_id'] = $appBaseId;
            $artificialOrderWhere['app_base_id'] = $appBaseId;
        } else {
            $this->error('未选择app!');
        }
        if ($partnerName != '') {
            $partnerInfo = \app\admin\model\Partner::get(['name' => $partnerName]);
            if (empty($partnerInfo)) {
                $this->success('列表', '', $list);
            }
            $accountWhere['partner_id'] = $partnerInfo['id'];
            $personnelAccountWhere['partner_id'] = $partnerInfo['id'];
            $personnelWhere['partner_id'] = $partnerInfo['id'];
        }
        if ($serviceGroupName != '') {
            $groupInfo = \app\admin\model\CustomerServiceGroup::get(['name' => $serviceGroupName]);
            if (empty($groupInfo)) {
                $this->success('列表', '', $list);
            }
            $accountWhere['customer_service_group_id'] = $groupInfo['id'];
            $personnelAccountWhere['customer_service_group_id'] = $groupInfo['id'];
            $personnelWhere['customer_service_group_id'] = $groupInfo['id'];
        }
        //查找客服人员
        if ($servicePersonnelName != '') {
            $personnelInfo = \app\admin\model\CustomerServicePersonnel::get(['name' => $servicePersonnelName]);
            if (empty($personnelInfo)) {
                $this->success('列表', '', $list);
            }
            $accountWhere['customer_service_personnel_id'] = $personnelInfo['id'];
            $personnelAccountWhere['customer_service_personnel_id'] = $personnelInfo['id'];
            $personnelWhere['id'] = $personnelInfo['id'];
        }
        //查找客服账号
        if ($serviceAccountName != '') {
            $this->error('多账号不支持客服账号查找!');
//            $accountWhere['username'] = $serviceAccountName;
        }
        //时间筛选（范围）
        if ($startOpenTime != '' && $endOpenTime != '') {
            $startOpenTime = strtotime($startOpenTime . '00:00:00');//格式化开始时间
            $endOpenTime = strtotime($endOpenTime . '23:59:59');//格式化结束时间
            $distributionUserWhere['create_time'] = ['between', [$startOpenTime, $endOpenTime]];
            $contactUserWhere['create_time'] = ['between', [$startOpenTime, $endOpenTime]];
            $sysPayViewWhere['update_time'] = ['between', [$startOpenTime, $endOpenTime]];
            $sysOrderWhere['pay_success_time'] = ['between', [$startOpenTime, $endOpenTime]];
            $artificialPayViewWhere['update_time'] = ['between', [$startOpenTime, $endOpenTime]];
            $artificialOrderWhere['pay_success_time'] = ['between', [$startOpenTime, $endOpenTime]];
        }
        $country_config_id = $this->request->post('country_config_id', '');
        if (empty($country_config_id)) {
            $country_name = '未知';

        } else {
            if ($country_config_id == 1) {
                $country_name = '印度';
            } else {
                $country_name = '墨西哥';
            }
            $distributionUserWhere['country_config_id'] = $country_config_id;
            $contactUserWhere['country_config_id'] = $country_config_id;
            $sysPayViewWhere['country_config_id'] = $country_config_id;
            $sysOrderWhere['country_config_id'] = $country_config_id;
            $artificialPayViewWhere['country_config_id'] = $country_config_id;
            $artificialOrderWhere['country_config_id'] = $country_config_id;
        }

//        $accountList = CustomerServiceAccount::with(['CustomerServiceAccountMiddle', 'CustomerServicePersonnel', 'CustomerServiceGroup', 'Partner'])->where($accountWhere)->select()->toArray();
        $personnelList = CustomerServicePersonnel::with(['CustomerServiceGroup', 'Partner'])->where($personnelWhere)->select()->toArray();
        //已分配用户数
        $distributionUserList = User::field('count(id) as user_num,customer_service_account_middle_id')
            ->where($distributionUserWhere)
            ->group('customer_service_account_middle_id')
            ->select();

        $distributionUserList = empty($distributionUserList) ? [] : array_column($distributionUserList->toArray(), null, 'customer_service_account_middle_id');
        //联系客服的用户数
        $contactUserList = User::field('count(id) as user_num,customer_service_account_middle_id')
            ->where($contactUserWhere)
            ->group('customer_service_account_middle_id')
            ->select();
        $contactUserList = empty($contactUserList) ? [] : array_column($contactUserList->toArray(), null, 'customer_service_account_middle_id');

        //系统支付页面数量
        $sysPayViewList = \app\admin\model\PayView::field('count(id) as pay_view_num,customer_service_personnel_id')
            ->where($sysPayViewWhere)
            ->group('customer_service_personnel_id')
            ->select();
        $sysPayViewList = empty($sysPayViewList) ? [] : array_column($sysPayViewList->toArray(), null, 'customer_service_personnel_id');

        //系统订单支付金额
        $sysOrderList = Order::field('sum(real_amount) as order_amount,customer_service_personnel_id')
            ->where($sysOrderWhere)
            ->group('customer_service_personnel_id')
            ->select();
        $sysOrderList = empty($sysOrderList) ? [] : array_column($sysOrderList->toArray(), null, 'customer_service_personnel_id');

        //人工支付页面数量
        $artificialPayViewList = \app\admin\model\PayView::field('count(id) as pay_view_num,customer_service_personnel_id')
            ->where($artificialPayViewWhere)
            ->group('customer_service_personnel_id')
            ->select();
        $artificialPayViewList = empty($artificialPayViewList) ? [] : array_column($artificialPayViewList->toArray(), null, 'customer_service_personnel_id');

        //人工支付订单金额
        $artificialOrderList = Order::field('sum(real_amount) as order_amount,customer_service_personnel_id')
            ->where($artificialOrderWhere)
            ->group('customer_service_personnel_id')
            ->select();
        $artificialOrderList = empty($artificialOrderList) ? [] : array_column($artificialOrderList->toArray(), null, 'customer_service_personnel_id');

        //最终返回数据 空数组自定义

        foreach ($personnelList as $value) {
            $personnelAccountWhere['customer_service_personnel_id'] = $value['id'];
            $personnelAccountList = CustomerServiceAccount::with(['CustomerServiceAccountMiddle'])->where($personnelAccountWhere)->select()->toArray();
            $personnelAccountNum = CustomerServiceAccount::with(['CustomerServiceAccountMiddle'])->where($personnelAccountWhere)->count();
            if (empty($personnelAccountNum)) {
                continue;
            }
            $distribution_user_num = 0;
            $contact_service_personnel_num = 0;

            foreach ($personnelAccountList as $v) {
                $distribution_user_num = $distribution_user_num + (empty($distributionUserList[$v['customer_service_account_middle_id']]) ? 0 : $distributionUserList[$v['customer_service_account_middle_id']]['user_num']);
                $contact_service_personnel_num = $contact_service_personnel_num + (empty($contactUserList[$v['customer_service_account_middle_id']]) ? 0 : $contactUserList[$v['customer_service_account_middle_id']]['user_num']);
            }
            $info = [
                'account_name' => $personnelAccountNum . '个',
                'partner_name' => $value['partner_name'],
                'group_name' => $value['group_name'],
                'personnel_name' => $value['name'],
                'distribution_user_num' => $distribution_user_num,
                'contact_service_personnel_num' => $contact_service_personnel_num,
                'sys_pay_view_num' => empty($sysPayViewList[$value['id']]) ? 0 : $sysPayViewList[$value['id']]['pay_view_num'],
                'sys_order_amount' => empty($sysOrderList[$value['id']]) ? 0 : $sysOrderList[$value['id']]['order_amount'],
                'artificial_pay_view_num' => empty($artificialPayViewList[$value['id']]) ? 0 : $artificialPayViewList[$value['id']]['pay_view_num'],
                'artificial_order_amount' => empty($artificialOrderList[$value['id']]) ? 0 : $artificialOrderList[$value['id']]['order_amount'],
            ];
            //计算总金额
            $info['total_amount'] = $info['sys_order_amount'] + $info['artificial_order_amount'];
            //计算人均
            if (empty($info['total_amount']) || empty($info['distribution_user_num'])) {
                $info['per_amount'] = 0;
            } else {
                $info['per_amount'] = round($info['total_amount'] / $info['distribution_user_num'], 2);
            }
            $info['country_name'] = $country_name;
            $list[] = $info;
        }
        $order = empty($order) ? 'total_amount' : $order;
        $sort = empty($sort) ? 'SORT_DESC' : $sort;
        $list = arraySequence($list, $order, $sort);
        $totalInfo = [
            'distribution_user_num_total' => 0,
            'contact_service_personnel_num_total' => 0,
            'sys_pay_view_num_total' => 0,
            'sys_order_amount_total' => 0,
            'artificial_pay_view_num_total' => 0,
            'artificial_order_amount_total' => 0,
            'total_amount_total' => 0,
            'per_amount_total' => 0,
        ];
        if (!empty($list)) {
            $totalInfo['distribution_user_num_total'] = array_sum(array_column($list, 'distribution_user_num'));
            $totalInfo['contact_service_personnel_num_total'] = array_sum(array_column($list, 'contact_service_personnel_num'));
            $totalInfo['sys_pay_view_num_total'] = array_sum(array_column($list, 'sys_pay_view_num'));
            $totalInfo['sys_order_amount_total'] = array_sum(array_column($list, 'sys_order_amount'));
            $totalInfo['artificial_pay_view_num_total'] = array_sum(array_column($list, 'artificial_pay_view_num'));
            $totalInfo['artificial_order_amount_total'] = array_sum(array_column($list, 'artificial_order_amount'));
            $totalInfo['total_amount_total'] = array_sum(array_column($list, 'total_amount'));
            if (empty($totalInfo['total_amount_total']) || empty($totalInfo['distribution_user_num_total'])) {
                $totalInfo['per_amount_total'] = 0;
            } else {
                $totalInfo['per_amount_total'] = round($totalInfo['total_amount_total'] / $totalInfo['distribution_user_num_total'], 2);
            }
        }
        $data = [
            'list' => $list,
            'total' => $totalInfo
        ];
        $this->success('获取成功', '', $data);
    }

    //查看当日已分配用户数
    public static function getAssignedUserNum($accountList)
    {
        $assigned_user_num = 0;
        $startOpenTime = strtotime(date('Y-m-d', time()) . '00:00:00');//格式化开始时间
        $endOpenTime = strtotime(date('Y-m-d', time()) . '23:59:59');//格式化结束时间
        if (!empty($accountList)) {
            $accountList = $accountList->toArray();
            $accountMiddleIds = array_column($accountList, 'customer_service_account_middle_id');
            $assigned_user_num = \app\admin\model\User::where([
                'customer_service_account_middle_id' => ['in', $accountMiddleIds],
                'create_time' => ['between', [$startOpenTime, $endOpenTime]]
            ])
                ->count('id');
        }
        return $assigned_user_num;
    }

    /**
     * 首页统计  用户数 合作团队数  客服人员数 客服账号数  今日登录数  今日注册数  三日新增数  七日新增数  七日活跃 月活跃
     */
    public function getIndexStatistics()
    {
        $data = [];
        //当天的开始时间 结束时间
        $startOpenTime = date('Y-m-d', time());
        $endOpenTime = date('Y-m-d', time());

        $startOpenTime = strtotime($startOpenTime . '00:00:00');//格式化开始时间
        $endOpenTime = strtotime($endOpenTime . '23:59:59');//格式化结束时间
        //三日前的开始时间
        $threeStartTime = strtotime(date('Y-m-d', strtotime('-3 day')) . '00:00:00');
        //七日前的开始时间
        $sevenStartTime = strtotime(date('Y-m-d', strtotime('-7 day')) . '00:00:00');
        //本月的开始时间
        $monthStartTime = mktime(0, 0, 0, date('m'), 1, date('Y'));
        //首页统计  用户数 合作团队数  客服人员数 客服账号数  今日登录数  今日注册数  三日新增数  七日新增数  七日活跃 月活跃
        //总用户数
//        $data['total_user_num'] = User::field('id')->count();
        $data['total_user_num'] = 0;
        //合作团队总数
        $partner_where = [
            'is_del' => 0
        ];
        $data['total_partner_num'] = \app\admin\model\Partner::field('id')->where($partner_where)->count();
        //客服人员总数
        $service_personnel_where = [
            'is_del' => 0,
            'switch' => 1,
        ];
        $data['total_service_personnel_num'] = CustomerServicePersonnel::field('id')->where($service_personnel_where)->count();
        //客服账号数量
        $service_account_where = [
            'is_del' => 0
        ];
        $data['total_service_account_num'] = CustomerServiceAccount::field('id')->where($service_account_where)->count();
        //今日登录数量
        $today_user_login_where = [
            'logintime' => ['between', [$startOpenTime, $endOpenTime]]
        ];
        $data['today_user_login_num'] = User::field('id')->where($today_user_login_where)->count();
        //今日注册数量
        $today_user_register_where = [
            'create_time' => ['between', [$startOpenTime, $endOpenTime]]
        ];
        $data['today_user_register_num'] = User::field('id')->where($today_user_register_where)->count();
        //三日新增
        $three_user_register_where = [
            'create_time' => ['between', [$threeStartTime, $endOpenTime]]
        ];
        $data['three_user_register_num'] = User::field('id')->where($three_user_register_where)->count();
        //七日新增
        $seven_user_register_where = [
            'create_time' => ['between', [$sevenStartTime, $endOpenTime]]
        ];
        $data['seven_user_register_num'] = User::field('id')->where($seven_user_register_where)->count();
        //七日活跃
        $seven_user_active_where = [
            'prevtime' => ['between', [$sevenStartTime, $endOpenTime]]
        ];
        $data['seven_user_active_num'] = User::field('id')->where($seven_user_active_where)->count();
        //月活跃
        $month_user_active_where = [
            'prevtime' => ['between', [$monthStartTime, $endOpenTime]]
        ];
        $data['month_user_active_num'] = User::field('id')->where($month_user_active_where)->count();
        $this->success('获取成功', '', $data);
    }

    /**
     * 折线图统计
     */
    public function getBrokenLineStatistics()
    {
        //折线图统计
        $list = [
            [
                'start_time' => strtotime(date('Y-m-d', strtotime('-6 day')) . '00:00:00'),
                'end_time' => strtotime(date('Y-m-d', strtotime('-6 day')) . '23:59:59'),
                'name' => 'seven'
            ],
            [
                'start_time' => strtotime(date('Y-m-d', strtotime('-5 day')) . '00:00:00'),
                'end_time' => strtotime(date('Y-m-d', strtotime('-5 day')) . '23:59:59'),
                'name' => 'six'
            ],
            [
                'start_time' => strtotime(date('Y-m-d', strtotime('-4 day')) . '00:00:00'),
                'end_time' => strtotime(date('Y-m-d', strtotime('-4 day')) . '23:59:59'),
                'name' => 'five'
            ],
            [
                'start_time' => strtotime(date('Y-m-d', strtotime('-3 day')) . '00:00:00'),
                'end_time' => strtotime(date('Y-m-d', strtotime('-3 day')) . '23:59:59'),
                'name' => 'four'
            ],
            [
                'start_time' => strtotime(date('Y-m-d', strtotime('-2 day')) . '00:00:00'),
                'end_time' => strtotime(date('Y-m-d', strtotime('-2 day')) . '23:59:59'),
                'name' => 'three'
            ],
            [
                'start_time' => strtotime(date('Y-m-d', strtotime('-1 day')) . '00:00:00'),
                'end_time' => strtotime(date('Y-m-d', strtotime('-1 day')) . '23:59:59'),
                'name' => 'two'
            ],
            [
                'start_time' => strtotime(date('Y-m-d', time()) . '00:00:00'),  //今天的开始时间
                'end_time' => strtotime(date('Y-m-d', time()) . '23:59:59'),   //今天的结束时间,
                'name' => 'one'
            ]
        ];

        $data = [];
        $loginData = [];
        $registerData = [];
        foreach ($list as $val) {
            $loginWhere = [
                'logintime' => ['between', [$val['start_time'], $val['end_time']]]
            ];
            $loginData[] = User::field('id')->where($loginWhere)->count();
            $registerWhere = [
                'create_time' => ['between', [$val['start_time'], $val['end_time']]]
            ];
            $registerData[] = User::field('id')->where($registerWhere)->count();
            $data[] = $val['name'];
        }
        $info = [
            'login_data' => $loginData,
            'register_data' => $registerData,
            'x_axis' => $data
        ];
        $this->success('获取成功', '', $info);
    }

    //单独人员统计(详细到每日)
    public function personnelStatistics()
    {
        $list = [];
        $totalInfo = [
            'distribution_user_num_total' => 0,
            'sys_pay_view_num_total' => 0,
            'sys_order_amount_total' => 0,
            'artificial_pay_view_num_total' => 0,
            'artificial_order_amount_total' => 0,
            'total_amount_total' => 0,
            'artificial_per_amount_total' => 0,
            'per_amount_total' => 0,
            'cost' => 0,
            'rmb_total_amount_total' => 0,
            'user_cost_total' => 0,
            'rmb_income_total' => 0
        ];
        //人员名字
        $name = $this->request->post('name', '');
        if (empty($name)) {
            $data = [
                'list' => $list,
                'total' => $totalInfo
            ];
            $this->success('获取成功', '', $data);
        }
        $appBaseId = $this->request->post('app_base_id', '');
        if ($appBaseId == '') {
            $this->error('未选择app!');
        }
        //时间
        $startOpenTime = $this->request->post('start_time', date('Y-m-d', time()));
        $endOpenTime = $this->request->post('end_time', date('Y-m-d', time()));
        $row = CustomerServicePersonnel::get(['name' => $name]);
        if (empty($row)) {
            $this->error('用户不存在!');
        }
        $res = $this->getPersonnelStatisticsInfo($row['id'], $startOpenTime, $endOpenTime, $appBaseId);
        $list = $res['list'];
        $date_cost = $res['date_cost'];
        if (!empty($list)) {
            $totalInfo['distribution_user_num_total'] = array_sum(array_column($list, 'distribution_user_num'));
            $totalInfo['sys_pay_view_num_total'] = array_sum(array_column($list, 'sys_pay_view_num'));
            $totalInfo['sys_order_amount_total'] = array_sum(array_column($list, 'sys_order_amount'));
            $totalInfo['artificial_pay_view_num_total'] = array_sum(array_column($list, 'artificial_pay_view_num'));
            $totalInfo['artificial_order_amount_total'] = array_sum(array_column($list, 'artificial_order_amount'));
            $totalInfo['total_amount_total'] = array_sum(array_column($list, 'total_amount'));
            $totalInfo['cost'] = $date_cost;
            //计算毛收入
            $totalInfo['rmb_total_amount_total'] = round(exchangeRateConversion($totalInfo['total_amount_total']), 2);
            //计算用户成本
            $totalInfo['user_cost_total'] = round($totalInfo['distribution_user_num_total'] * $date_cost, 2);
            //计算净收入
            $totalInfo['rmb_income_total'] = round($totalInfo['rmb_total_amount_total'] - $totalInfo['user_cost_total'], 2);
            if (empty($totalInfo['artificial_order_amount_total']) || empty($totalInfo['distribution_user_num_total'])) {
                $totalInfo['artificial_per_amount_total'] = 0;
            } else {
                $totalInfo['artificial_per_amount_total'] = round($totalInfo['artificial_order_amount_total'] / $totalInfo['distribution_user_num_total'], 2);
            }
            if (empty($totalInfo['total_amount_total']) || empty($totalInfo['distribution_user_num_total'])) {
                $totalInfo['per_amount_total'] = 0;
            } else {
                $totalInfo['per_amount_total'] = round($totalInfo['total_amount_total'] / $totalInfo['distribution_user_num_total'], 2);
            }
        }
        $data = [
            'list' => $list,
            'total' => $totalInfo
        ];
        $this->success('获取成功', '', $data);
    }

    //获取人员统计详情
    public function getPersonnelStatisticsInfo($id, $startOpenTime, $endOpenTime, $appBaseId)
    {
//        $accountInfo = CustomerServiceAccount::field('id')->where([
//            'customer_service_personnel_id' => $id,
//            'switch' => 1,
//            'app_base_id' => $appBaseId
//        ])
//            ->find();
//        if (empty($accountInfo)) {
//            $this->error('当前客服未添加客服账号');
//        }
//        $accountMiddleInfo = CustomerServiceAccountMiddle::where([
//            'customer_service_account_id' => $accountInfo['id']
//        ])
//            ->find();
        $accountInfo = \app\admin\model\CustomerServiceAccount::field('id')->where([
            'customer_service_personnel_id' => $id,
            'switch' => 1,
            'app_base_id' => $appBaseId

        ])
            ->select();
        if (empty($accountInfo)) {
            $this->error('当前客服未添加客服账号');
        }
        $accountInfo = $accountInfo->toArray();
        $accountIds = array_column($accountInfo, 'id');
        $accountMiddleInfo = CustomerServiceAccountMiddle::where([
            'customer_service_account_id' => ['in', $accountIds]
        ])
            ->select()->toArray();
        $accountMiddleIds = array_column($accountMiddleInfo, 'id');
        //获取两个日期
        $dateList = printDates($startOpenTime, $endOpenTime);
        $list = [];
        $dateCostTotal = 0;
        foreach ($dateList as $value) {
            $info['date'] = $value['date'];
            //已分配客服数
//            $distributionUserWhere = [
//                'create_time' => ['between', [$value['start_time'], $value['end_time']]],
//                'customer_service_account_middle_id' => $accountMiddleInfo['id']
//            ];
            $distributionUserWhere = [
                'create_time' => ['between', [$value['start_time'], $value['end_time']]],
                'customer_service_account_middle_id' => ['in', $accountMiddleIds],
            ];
            $info['distribution_user_num'] = User::where($distributionUserWhere)->count('id');
            //系统生成支付页面
            $sysPayViewWhere = [
                'update_time' => ['between', [$value['start_time'], $value['end_time']]],
                'customer_service_personnel_id' => $id,
                'generate_type' => 1,
                'status' => 3,
                'app_base_id' => $appBaseId
            ];
            $info['sys_pay_view_num'] = \app\admin\model\PayView::where($sysPayViewWhere)->count('id');
            //系统订单支付金额
            $sysOrderWhere = [
                'pay_success_time' => ['between', [$value['start_time'], $value['end_time']]],
                'customer_service_personnel_id' => $id,
                'generate_type' => 1,
                'status' => 3,
                'app_base_id' => $appBaseId
            ];
            $info['sys_order_amount'] = Order::where($sysOrderWhere)->sum('real_amount');
            //人工生成支付页面
            $artificialPayViewWhere = [
                'update_time' => ['between', [$value['start_time'], $value['end_time']]],
                'customer_service_personnel_id' => $id,
                'generate_type' => 2,
                'status' => 3,
                'app_base_id' => $appBaseId
            ];
            $info['artificial_pay_view_num'] = \app\admin\model\PayView::where($artificialPayViewWhere)->count('id');;
            //人工支付订单金额
            $artificialOrderWhere = [
                'pay_success_time' => ['between', [$value['start_time'], $value['end_time']]],
                'customer_service_personnel_id' => $id,
                'generate_type' => 2,
                'status' => 3,
                'app_base_id' => $appBaseId
            ];
            $info['artificial_order_amount'] = Order::where($artificialOrderWhere)->sum('real_amount');
            //计算总金额
            $info['total_amount'] = $info['sys_order_amount'] + $info['artificial_order_amount'];
            //计算人工订单人均
            if (empty($info['artificial_order_amount']) || empty($info['distribution_user_num'])) {
                $info['artificial_per_amount'] = 0;
            } else {
                $info['artificial_per_amount'] = round($info['artificial_order_amount'] / $info['distribution_user_num'], 2);
            }
            //计算人均
            if (empty($info['total_amount']) || empty($info['distribution_user_num'])) {
                $info['per_amount'] = 0;
            } else {
                $info['per_amount'] = round($info['total_amount'] / $info['distribution_user_num'], 2);
            }
            //每日成本
            $distributionCostWhere = [
                'time' => ['between', [$value['start_time'], $value['end_time']]],
                'app_base_id' => $appBaseId
            ];
            $cost = \app\admin\model\Cost::where($distributionCostWhere)->find();
            $info['cost'] = empty($cost['cost']) ? 0 : $cost['cost'];
            $dateCostTotal = $dateCostTotal + $info['cost'];
            //计算毛收入
            $info['rmb_total_amount'] = round(exchangeRateConversion($info['total_amount']), 2);
            //计算用户成本
            $info['user_cost'] = round($info['distribution_user_num'] * $info['cost'], 2);
            //计算净收入
            $info['rmb_income'] = round($info['rmb_total_amount'] - $info['user_cost'], 2);
            $list[] = $info;
        }
        $dateCount = count($dateList);
        $dateCost = empty($dateCostTotal) ? 0 : round($dateCostTotal / $dateCount, 2);
        return ['list' => $list, 'date_cost' => $dateCost];
    }

    //客服组统计(详细到每日)
    public function groupStatistics()
    {
        $list = [];
        $totalInfo = [
            'distribution_user_num_total' => 0,
            'sys_pay_view_num_total' => 0,
            'sys_order_amount_total' => 0,
            'artificial_pay_view_num_total' => 0,
            'artificial_order_amount_total' => 0,
            'total_amount_total' => 0,
            'artificial_per_amount_total' => 0,
            'per_amount_total' => 0,
            'cost' => 0,
            'rmb_total_amount_total' => 0,
            'user_cost_total' => 0,
            'rmb_income_total' => 0
        ];
        $appBaseId = $this->request->post('app_base_id', '');
        if ($appBaseId == '') {
            $this->error('未选择app!');
        }
        //人员名字
        $name = $this->request->post('name', '');
        //时间
        $startOpenTime = $this->request->post('start_time', date('Y-m-d', time()));
        $endOpenTime = $this->request->post('end_time', date('Y-m-d', time()));
        if (empty($name)) {
            $data = [
                'list' => $list,
                'total' => $totalInfo
            ];
            $this->success('获取成功', '', $data);
        }
        $row = CustomerServiceGroup::get(['name' => $name]);
        if (empty($row)) {
            $this->error('客服组不存在!');
        }
        //查找客服组下所有的打开的客服账号
        $accountList = CustomerServiceAccount::with(['CustomerServiceAccountMiddle'])
            ->where([
                'switch' => 1,
                'customer_service_group_id' => $row['id'],
                'app_base_id' => $appBaseId
            ])->select();
        if (empty($accountList)) {
            $this->error('客服组下无使用中的账号!');
        }
        $accountMiddleIds = array_column($accountList->toArray(), 'customer_service_account_middle_id');
        $Info = $this->getGroupStatisticsInfo($row['id'], $accountMiddleIds, $startOpenTime, $endOpenTime, $appBaseId);
        $list = $Info['list'];
        if (!empty($list)) {
            $totalInfo['distribution_user_num_total'] = array_sum(array_column($list, 'distribution_user_num'));
            $totalInfo['sys_pay_view_num_total'] = array_sum(array_column($list, 'sys_pay_view_num'));
            $totalInfo['sys_order_amount_total'] = array_sum(array_column($list, 'sys_order_amount'));
            $totalInfo['artificial_pay_view_num_total'] = array_sum(array_column($list, 'artificial_pay_view_num'));
            $totalInfo['artificial_order_amount_total'] = array_sum(array_column($list, 'artificial_order_amount'));
            $totalInfo['total_amount_total'] = array_sum(array_column($list, 'total_amount'));
            $totalInfo['cost'] = empty($Info['date_cost']) ? 0 : $Info['date_cost'];
            //计算毛收入
            $totalInfo['rmb_total_amount_total'] = round(exchangeRateConversion($totalInfo['total_amount_total']), 2);
            //计算用户成本
            $totalInfo['user_cost_total'] = round($totalInfo['distribution_user_num_total'] * $totalInfo['cost'], 2);
            //计算净收入
            $totalInfo['rmb_income_total'] = round($totalInfo['rmb_total_amount_total'] - $totalInfo['user_cost_total'], 2);
            if (empty($totalInfo['artificial_order_amount_total']) || empty($totalInfo['distribution_user_num_total'])) {
                $totalInfo['artificial_per_amount_total'] = 0;
            } else {
                $totalInfo['artificial_per_amount_total'] = round($totalInfo['artificial_order_amount_total'] / $totalInfo['distribution_user_num_total'], 2);
            }
            if (empty($totalInfo['total_amount_total']) || empty($totalInfo['distribution_user_num_total'])) {
                $totalInfo['per_amount_total'] = 0;
            } else {
                $totalInfo['per_amount_total'] = round($totalInfo['total_amount_total'] / $totalInfo['distribution_user_num_total'], 2);
            }
        }
        $data = [
            'list' => $list,
            'total' => $totalInfo
        ];
        $this->success('获取成功', '', $data);

    }

    //获取客服组统计详情
    public function getGroupStatisticsInfo($id, $accountMiddleIds, $startOpenTime, $endOpenTime, $appBaseId)
    {
        //获取两个日期
        $dateList = printDates($startOpenTime, $endOpenTime);
        $list = [];
        $dateCostTotal = 0;
        foreach ($dateList as $value) {
            $info = [];
            $info['date'] = $value['date'];
            //已分配客服数
            $distributionUserWhere = [
                'create_time' => ['between', [$value['start_time'], $value['end_time']]],
                'customer_service_account_middle_id' => ['in', $accountMiddleIds]
            ];
            $info['distribution_user_num'] = User::where($distributionUserWhere)->count('id');
            //系统生成支付页面
            $sysPayViewWhere = [
                'update_time' => ['between', [$value['start_time'], $value['end_time']]],
                'customer_service_group_id' => $id,
                'generate_type' => 1,
                'status' => 3,
                'app_base_id' => $appBaseId
            ];
            $info['sys_pay_view_num'] = \app\admin\model\PayView::where($sysPayViewWhere)->count('id');
            //系统订单支付金额
            $sysOrderWhere = [
                'pay_success_time' => ['between', [$value['start_time'], $value['end_time']]],
                'customer_service_group_id' => $id,
                'generate_type' => 1,
                'status' => 3,
                'app_base_id' => $appBaseId
            ];
            $info['sys_order_amount'] = Order::where($sysOrderWhere)->sum('real_amount');
            //人工生成支付页面
            $artificialPayViewWhere = [
                'update_time' => ['between', [$value['start_time'], $value['end_time']]],
                'customer_service_group_id' => $id,
                'generate_type' => 2,
                'status' => 3,
                'app_base_id' => $appBaseId
            ];
            $info['artificial_pay_view_num'] = \app\admin\model\PayView::where($artificialPayViewWhere)->count('id');;
            //人工支付订单金额
            $artificialOrderWhere = [
                'pay_success_time' => ['between', [$value['start_time'], $value['end_time']]],
                'customer_service_group_id' => $id,
                'generate_type' => 2,
                'status' => 3,
                'app_base_id' => $appBaseId
            ];

            $info['artificial_order_amount'] = Order::where($artificialOrderWhere)->sum('real_amount');
            //计算总金额
            $info['total_amount'] = $info['sys_order_amount'] + $info['artificial_order_amount'];
            //每日成本
            $distributionCostWhere = [
                'time' => ['between', [$value['start_time'], $value['end_time']]],
                'app_base_id' => $appBaseId
            ];
            $cost = \app\admin\model\Cost::where($distributionCostWhere)->find();
            $info['cost'] = empty($cost['cost']) ? 0 : $cost['cost'];
            $dateCostTotal = $dateCostTotal + $info['cost'];
            //计算毛收入
            $info['rmb_total_amount'] = round(exchangeRateConversion($info['total_amount']), 2);
            //计算用户成本
            $info['user_cost'] = round($info['distribution_user_num'] * $info['cost'], 2);
            //计算净收入
            $info['rmb_income'] = round($info['rmb_total_amount'] - $info['user_cost'], 2);
            //计算人工订单人均
            if (empty($info['artificial_order_amount']) || empty($info['distribution_user_num'])) {
                $info['artificial_per_amount'] = 0;
            } else {
                $info['artificial_per_amount'] = round($info['artificial_order_amount'] / $info['distribution_user_num'], 2);
            }
            //计算人均
            if (empty($info['total_amount']) || empty($info['distribution_user_num'])) {
                $info['per_amount'] = 0;
            } else {
                $info['per_amount'] = round($info['total_amount'] / $info['distribution_user_num'], 2);
            }
            $list[] = $info;
        }
        $dateCount = count($dateList);
        $dateCost = empty($dateCostTotal) ? 0 : round($dateCostTotal / $dateCount, 2);
        return ['list' => $list, 'date_cost' => $dateCost];
    }

    //根据借款金额区间去得到用户支付金额
    public function getStatisticsPayInfo()
    {
        if ($this->request->isPost()) {
            $min_amount = $this->request->post('min_amount', 50000);
            $max_amount = $this->request->post('max_amount', 1000000);

            $list = Db::table('su_user')
                ->field('su_user.id')
                ->join('su_loan_order', 'su_loan_order.user_id = su_user.id AND su_loan_order.amount_money between ' . $min_amount . ' and ' . $max_amount, 'left')
                ->where('su_user.is_pay', '=', '1')
                ->select()->toArray();
            $user_ids = array_column($list, 'id');
            $userNum = count($user_ids);
            $payAmountTotal = \app\admin\model\PayView::where(['user_id' => ['in', $user_ids], 'status' => '3'])->sum('amount_money');
            $data = [
                'user_num' => $userNum,
                'amount_total' => $payAmountTotal,
                'per_capita' => round($payAmountTotal / $userNum, 2)
            ];
            $this->success('获取成功', '', $data);
        }
    }

    //adjust上报统计
    public function adjustEscalationStatistics()
    {
        $eventArr = [
            //贷款金额
            'dk_money',
            //贷款订单(支付成功)
            'dk_order_nums',
            //贷款用户人数(支付成功)
            'dk_user_nums',
            //还款金额 触发条件(还款类别的支付订单成功后记录支付金额)
            'hk_money',
            //还款订单数(支付成功) 触发条件(还款类别的支付订单成功后记录)
            'hk_order_nums',
            //还款用户人数(支付成功) 触发条件(还款类别的支付订单首次成功后记录)
            'hk_user_nums',
            //总计金额 触发条件(每次支付成功后记录支付金额)
            'income',
            //提交个人信息  触发条件(提交个人信息)
            'info',
            //注册  触发条件(注册 app端触发)
            'reg',
            //是否成为会员 触发条件(会员费支付成功)
            'is_vip',
            //支付订单数量 触发条件(只要支付成功就记录一次)
            'pay_order_nums',
            //支付人数 触发条件(用户首次支付成功 记录一次)
            'pay_user_nums',
            //提现金额  触发条件(提现类别的支付订单成功后记录支付金额)
            'tx_money',
            //提现订单数(支付成功) 触发条件(提现类别的支付订单成功后记录)
            'tx_order_nums',
            //提现用户人数(支付成功) 触发条件(提现类别的支付订单首次成功后记录)
            'tx_user_nums',
            //会员金额(会员支付成功) 触发条件(会员类别的支付订单首次成功后记录)
            'vip_money',
            //会员金额(会员支付成功) 触发条件(会员类别的支付订单首次成功后记录)
            '1W',
            '5K',
            //上报人工支付订单数
            'is_artificial_order_nums',
            //上报人工收款金额
            'is_artificial_money',
            //上报人工订单支付人数
            'is_artificial_user_nums',
            //上报人工订单支付人数
            'old_pay_user_money',
            //上报人工订单支付人数
            'old_pay_user_num',
            //历史新用户支付会员费
            'new_pay_vip_user_money',
            //历史新用户支付人数
            'new_pay_vip_user_num',
            //历史新用户支付人工费
            'new_pay_user_money',
            //历史新用户支付人工人数
            'new_pay_user_num',
            //第一次人工
            'pua_1',
            //第二次人工
            'pua_2',
            //第三次人工
            'pua_3',
        ];
        //时间
        $startTime = $this->request->post('start_time', date('Y-m-d', time()));
        $endTime = $this->request->post('end_time', date('Y-m-d', time()));
        $startTime = strtotime($startTime . '00:00:00');//格式化开始时间
        $endTime = strtotime($endTime . '23:59:59');//格式化结束时间
        $appBaseId = $this->request->post('app_base_id', '');
        if ($appBaseId == '') {
            $this->error('未选择app!');
        }
        //获取
        $list = [];
        foreach ($eventArr as $key => $value) {
            $data = [
                'event' => $value
            ];
            //上报数量
            $escalationTotalNumWhere = [
                'create_time' => ['between', [$startTime, $endTime]],
                'identify' => $value,
                'app_base_id' => $appBaseId
            ];
            $data['escalationTotalNum'] = AdjustLog::field('id')->where($escalationTotalNumWhere)->count();
            //上报金额
            $data['escalationTotalAmountMoney'] = AdjustLog::field('id,amount_money')->where($escalationTotalNumWhere)->sum('amount_money');
            //上报成功数量
            $escalationSuccessTotalNumWhere = [
                'create_time' => ['between', [$startTime, $endTime]],
                'identify' => $value,
                'status' => 1,
                'app_base_id' => $appBaseId
            ];
            $data['escalationSuccessTotalNum'] = AdjustLog::field('id')->where($escalationSuccessTotalNumWhere)->count();
            //上报成功金额
            $data['escalationSuccessTotalAmountMoney'] = AdjustLog::field('id,amount_money')->where($escalationSuccessTotalNumWhere)->sum('amount_money');
            //上报失败数量
            $escalationErrorTotalNumWhere = [
                'create_time' => ['between', [$startTime, $endTime]],
                'identify' => $value,
                'status' => 0,
                'app_base_id' => $appBaseId
            ];
            $data['escalationErrorTotalNum'] = AdjustLog::field('id')->where($escalationErrorTotalNumWhere)->count();
            //上报失败金额
            $data['escalationErrorTotalAmountMoney'] = AdjustLog::field('id,amount_money')->where($escalationErrorTotalNumWhere)->sum('amount_money');
            $list[] = $data;
        }
        $this->success('获取成功', '', $list);
    }

    //客服组总计
    public function getGroupStatisticsList()
    {
        $list = [];

        //人员名字
        $name = $this->request->post('name', '');
        $appBaseId = $this->request->post('app_base_id', '');
        if ($appBaseId == '') {
            $this->error('未选择app!');
        }
        //时间
        $startOpenTime = $this->request->post('start_time', date('Y-m-d', time()));
        $endOpenTime = $this->request->post('end_time', date('Y-m-d', time()));
        if (empty($name)) {
            $list = CustomerServiceGroup::select()->toArray();
        } else {
            $name = explode(',', $name);
            $list = CustomerServiceGroup::where([
                'name' => ['in', $name]
            ])->select()->toArray();
        }

        if (empty($list)) {
            $this->error('客服组不存在!');
        }

        $groupIds = array_column($list, 'id');
        $resList = [];
        foreach ($groupIds as $key => $val) {
            $groupInfo = CustomerServiceGroup::get($val);
            //查找客服组下所有的打开的客服账号
            $accountList = CustomerServiceAccount::with(['CustomerServiceAccountMiddle'])
                ->where([
                    'switch' => 1,
                    'customer_service_group_id' => $val,
                    'app_base_id' => $appBaseId
                ])->select();
            if (empty($accountList)) {
                $info = $this->getTotalGroupStatisticsInfo($val, [], $startOpenTime, $endOpenTime, $appBaseId);
            } else {
                $accountMiddleIds = array_column($accountList->toArray(), 'customer_service_account_middle_id');

                $info = $this->getTotalGroupStatisticsInfo($val, $accountMiddleIds, $startOpenTime, $endOpenTime, $appBaseId);
            }
            $info['name'] = $groupInfo['name'];
            $resList[] = $info;
        }

        $totalInfo = [
            'distribution_user_num_total' => array_sum(array_column($resList, 'distribution_user_num')),
            'sys_pay_view_num_total' => array_sum(array_column($resList, 'sys_pay_view_num')),
            'sys_order_amount_total' => array_sum(array_column($resList, 'sys_order_amount')),
            'artificial_pay_view_num_total' => array_sum(array_column($resList, 'artificial_pay_view_num')),
            'artificial_order_amount_total' => array_sum(array_column($resList, 'artificial_order_amount')),
            'total_amount_total' => array_sum(array_column($resList, 'total_amount')),
//            'artificial_per_amount_total' => array_sum(array_column($resList, 'artificial_per_amount')),
//            'per_amount_total' => array_sum(array_column($resList, 'per_amount')),
            'cost' => empty($resList[0]['date_cost']) ? 0 : $resList[0]['date_cost'],
            'rmb_total_amount_total' => array_sum(array_column($resList, 'rmb_total_amount')),
            'user_cost_total' => array_sum(array_column($resList, 'user_cost')),
            'rmb_income_total' => array_sum(array_column($resList, 'rmb_income'))
        ];
        if (empty($totalInfo['artificial_order_amount_total']) || empty($totalInfo['distribution_user_num_total'])) {
            $totalInfo['artificial_per_amount_total'] = 0;
        } else {
            $totalInfo['artificial_per_amount_total'] = round($totalInfo['artificial_order_amount_total'] / $totalInfo['distribution_user_num_total'], 2);
        }
        if (empty($totalInfo['total_amount_total']) || empty($totalInfo['distribution_user_num_total'])) {
            $totalInfo['per_amount_total'] = 0;
        } else {
            $totalInfo['per_amount_total'] = round($totalInfo['total_amount_total'] / $totalInfo['distribution_user_num_total'], 2);
        }
        $data = [
            'list' => $resList,
            'total' => $totalInfo
        ];
        $this->success('获取成功', '', $data);
    }

    //获取客服组总计详情
    public function getTotalGroupStatisticsInfo($id, $accountMiddleIds, $startTime, $endTime, $appBaseId)
    {
        if (empty($accountMiddleIds)) {
            $info = [
                'distribution_user_num' => 0,
                'sys_pay_view_num' => 0,
                'sys_order_amount' => 0,
                'artificial_pay_view_num' => 0,
                'artificial_order_amount' => 0,
                'total_amount' => 0,
                'rmb_total_amount' => 0,
                'user_cost' => 0,
                'rmb_income' => 0,
                'artificial_per_amount' => 0,
                'per_amount' => 0

            ];
        }
        //获取两个日期
        $dateList = printDates($startTime, $endTime);
        $dateCostTotal = 0;
        foreach ($dateList as $value) {
            //每日成本
            $distributionCostWhere = [
                'time' => ['between', [$value['start_time'], $value['end_time']]],
                'app_base_id' => $appBaseId
            ];
            $cost = \app\admin\model\Cost::where($distributionCostWhere)->find();
            $cost = empty($cost['cost']) ? 0 : $cost['cost'];
            $dateCostTotal = $dateCostTotal + $cost;
        }
        $dateCount = count($dateList);
        $dateCost = empty($dateCostTotal) ? 0 : round($dateCostTotal / $dateCount, 2);
        //获取两个日期
        $startOpenTime = strtotime($startTime . '00:00:00');//格式化开始时间
        $endOpenTime = strtotime($endTime . '23:59:59');//格式化结束时间
        //已分配客服数
        $distributionUserWhere = [
            'create_time' => ['between', [$startOpenTime, $endOpenTime]],
            'customer_service_account_middle_id' => ['in', $accountMiddleIds]
        ];
        $info['distribution_user_num'] = User::where($distributionUserWhere)->count('id');
        //系统生成支付页面
        $sysPayViewWhere = [
            'update_time' => ['between', [$startOpenTime, $endOpenTime]],
            'customer_service_group_id' => $id,
            'generate_type' => 1,
            'status' => 3,
            'app_base_id' => $appBaseId
        ];
        $info['sys_pay_view_num'] = \app\admin\model\PayView::where($sysPayViewWhere)->count('id');
        //系统订单支付金额
        $sysOrderWhere = [
            'pay_success_time' => ['between', [$startOpenTime, $endOpenTime]],
            'customer_service_group_id' => $id,
            'generate_type' => 1,
            'status' => 3,
            'app_base_id' => $appBaseId
        ];
        $info['sys_order_amount'] = Order::where($sysOrderWhere)->sum('real_amount');
        //人工生成支付页面
        $artificialPayViewWhere = [
            'update_time' => ['between', [$startOpenTime, $endOpenTime]],
            'customer_service_group_id' => $id,
            'generate_type' => 2,
            'status' => 3,
            'app_base_id' => $appBaseId
        ];
        $info['artificial_pay_view_num'] = \app\admin\model\PayView::where($artificialPayViewWhere)->count('id');;
        //人工支付订单金额
        $artificialOrderWhere = [
            'pay_success_time' => ['between', [$startOpenTime, $endOpenTime]],
            'customer_service_group_id' => $id,
            'generate_type' => 2,
            'status' => 3,
            'app_base_id' => $appBaseId
        ];

        $info['artificial_order_amount'] = Order::where($artificialOrderWhere)->sum('real_amount');
        //计算总金额
        $info['total_amount'] = round($info['sys_order_amount'] + $info['artificial_order_amount'], 2);
        //单个用户平均成本
        $info['date_cost'] = $dateCost;
        //计算毛收入
        $info['rmb_total_amount'] = round(exchangeRateConversion($info['total_amount']), 2);
        //计算用户成本
        $info['user_cost'] = round($info['distribution_user_num'] * $dateCost, 2);
        //计算净收入
        $info['rmb_income'] = round($info['rmb_total_amount'] - $info['user_cost'], 2);
        //计算人工订单人均
        if (empty($info['artificial_order_amount']) || empty($info['distribution_user_num'])) {
            $info['artificial_per_amount'] = 0;
        } else {
            $info['artificial_per_amount'] = round($info['artificial_order_amount'] / $info['distribution_user_num'], 2);
        }
        //计算人均
        if (empty($info['total_amount']) || empty($info['distribution_user_num'])) {
            $info['per_amount'] = 0;
        } else {
            $info['per_amount'] = round($info['total_amount'] / $info['distribution_user_num'], 2);
        }
        return $info;
    }

    /**
     * 支付通道统计
     */
    public function getPayConfigStatisticsList()
    {
        //时间
        $startOpenTime = $this->request->post('start_time', date('Y-m-d', time()));
        $endOpenTime = $this->request->post('end_time', date('Y-m-d', time()));
        $partner_id = $this->request->post('partner_id', '');
        $customer_service_group_id = $this->request->post('customer_service_group_id', '');
//        if ($appBaseId == '') {
//            $this->error('未选择app!');
//        }
        //获取两个日期
        $dt_start = strtotime($startOpenTime . ' 00:00:00');
        $dt_end = strtotime($endOpenTime . ' 23:59:59');
        //获取支付通道列表
        $list = \app\admin\model\PayConfig::field('id,title,nickname,country_config_id')->where([
            'is_del' => 0
        ])->select()->toArray();
        $where = [
            'pay_success_time' => ['between', [$dt_start, $dt_end]],
            'status' => 3,
        ];
        if (!empty($partner_id)) {
            $where['partner_id'] = $partner_id;
        }
        if (!empty($customer_service_group_id)) {
            $where['customer_service_group_id'] = $customer_service_group_id;
        }
        foreach ($list as $key => $val) {
            $where['pay_config_id'] = $val['id'];
            $val['total_amount'] = Order::where($where)->sum('real_amount');
            $val['order_num'] = Order::where($where)->count();
            $list[$key] = $val;
        }
        $this->success('获取成功', '', $list);
    }

    //渠道统计
    public function channelStatisticsList()
    {
        $channelList = [
            'Organic',
            'Unattributed',
            'Google Ads',
            ''
        ];
        //时间
        $startOpenTime = $this->request->post('start_time', date('Y-m-d', time()));
        $endOpenTime = $this->request->post('end_time', date('Y-m-d', time()));
        $startTime = strtotime($startOpenTime . '00:00:00');//格式化开始时间
        $endTime = strtotime($endOpenTime . '23:59:59');//格式化结束时间
        $appBaseId = $this->request->post('app_base_id', '');
        if ($appBaseId == '') {
            $this->error('未选择app!');
        }
        $list = [];
        //TODO 由于添加用户的channel默认给值'' 所以用''搜索 其他默认是null
        foreach ($channelList as $value) {
            //已分配客服数
            $distributionUserWhere = [
                'create_time' => ['between', [$startTime, $endTime]],
                'channel' => $value
            ];
            $info['channel'] = empty($value) ? '未知' : $value;
            $info['distribution_user_num'] = User::where($distributionUserWhere)->count('id');

            //系统生成支付页面
            $sysPayViewWhere = [
                'update_time' => ['between', [$startTime, $endTime]],
                'channel' => empty($value) ? null : $value,
                'generate_type' => 1,
                'app_base_id' => $appBaseId
            ];
            if (empty($value)) {
                $sysPayViewWhere['channel'] = ['in', [$value, null]];
            }
            $info['sys_pay_view_num'] = \app\admin\model\PayView::where($sysPayViewWhere)->count('id');
            //系统订单支付金额
            $sysOrderWhere = [
                'pay_success_time' => ['between', [$startTime, $endTime]],
                'channel' => empty($value) ? null : $value,
                'generate_type' => 1,
                'status' => 3,
                'app_base_id' => $appBaseId
            ];
            if (empty($value)) {
                $sysOrderWhere['channel'] = ['in', [$value, null]];
            }
            $info['sys_order_amount'] = Order::where($sysOrderWhere)->sum('real_amount');
            //人工生成支付页面
            $artificialPayViewWhere = [
                'update_time' => ['between', [$startTime, $endTime]],
                'channel' => empty($value) ? null : $value,
                'generate_type' => 2,
                'status' => 3,
                'app_base_id' => $appBaseId
            ];
            if (empty($value)) {
                $artificialPayViewWhere['channel'] = ['in', [$value, null]];
            }
            $info['artificial_pay_view_num'] = \app\admin\model\PayView::where($artificialPayViewWhere)->count('id');;
            //人工支付订单金额

            $artificialOrderWhere = [
                'pay_success_time' => ['between', [$startTime, $endTime]],
                'channel' => empty($value) ? null : $value,
                'generate_type' => 2,
                'status' => 3,
                'app_base_id' => $appBaseId
            ];
            if (empty($value)) {
                $artificialOrderWhere['channel'] = ['in', [$value, null]];
            }
            $info['artificial_order_amount'] = Order::where($artificialOrderWhere)->sum('real_amount');
            //计算总金额
            $info['total_amount'] = round($info['sys_order_amount'] + $info['artificial_order_amount'], 2);
            //计算人工订单人均
            if (empty($info['artificial_order_amount']) || empty($info['distribution_user_num'])) {
                $info['artificial_per_amount'] = 0;
            } else {
                $info['artificial_per_amount'] = round($info['artificial_order_amount'] / $info['distribution_user_num'], 2);
            }
            //计算人均
            if (empty($info['total_amount']) || empty($info['distribution_user_num'])) {
                $info['per_amount'] = 0;
            } else {
                $info['per_amount'] = round($info['total_amount'] / $info['distribution_user_num'], 2);
            }
            $list[] = $info;
        }
        $data['list'] = $list;
        $this->success('获取成功', '', $data);
    }

    //算法首页统计接口
    public function suHomeStatistics()
    {
        //统计管理    统计内容

        $content = [];
        //  客服人员名字   当日接了多少人   联系客服数   支付成功总笔数  支付成功总金额   人均（金额除以接人数）
        if ($this->request->isPost()) {
            $params = $this->request->post();
            $time = isset($params["startTime"]) ? date('Y-m-d', strtotime($params["startTime"])) : date('Y-m-d');
            $endTime = isset($params["endTime"]) ? date('Y-m-d 23:59:59', strtotime($params["endTime"])) : date('Y-m-d 23:59:59');
            $where = [];
            if ($this->is_kefu && !$this->is_kefu_leader) {
                $where['customer_service_account_middle_id'] = $this->info['id'];
            }
            if (($this->is_kefu && $this->is_kefu_leader) || $this->is_admin) {
                $sWhere = [];
                if (!$this->is_admin) {
                    $sWhere['kefu_group_id'] = $this->info['kefu_group_id'];
                }
                $sWhere['is_del'] = 0;
                $sKefuUser = [];
                if (!empty($params['kefu_name'])) {
                    $sWhere['username'] = $params['kefu_name'];
                    $sKefuUser = Db::table('su_kefu_user')->where($sWhere)->select()->toArray();
                    if (empty($sKefuUser)) {
                        $this->success("", "", $content);
                    }
                }
                if (!empty($params['kefu_account']) && !empty($params['kefu_name'])) {
                    unset($sWhere['username']);
                    $sWhere['kefu_user_id'] = ['in', array_column($sKefuUser, 'id')];
                    $sWhere['kefu_account'] = $params['kefu_account'];
                    $sKefuAccount = Db::table('su_kefu_account')->where($sWhere)->select()->toArray();
                    if (empty($sKefuAccount)) {
                        $this->success("", "", $content);
                    }
                    $where['customer_service_account_middle_id'] = ['in', array_column($sKefuAccount, 'kefu_user_id')];

                } elseif (!empty($params['kefu_account']) && empty($params['kefu_name'])) {
                    $sWhere['kefu_account'] = $params['kefu_account'];
                    $sKefuAccount = Db::table('su_kefu_account')->where($sWhere)->select()->toArray();
                    if (empty($sKefuAccount)) {
                        $this->success("", "", $content);
                    }
                    $where['customer_service_account_middle_id'] = ['in', array_column($sKefuAccount, 'kefu_user_id')];
                }

            }

            $model = new UserInfo();
            $where['create_time'] = ['between', [$time, $endTime]];
            $list = $model->where($where)->field('count(1) as kefuCnt, customer_service_account_middle_id as kefu_id, sum(is_check_kf_switch) as contactCnt')->group('customer_service_account_middle_id')->select()->toArray();
            $kefuList = Db::table('su_kefu_user')->where('id', 'in', array_column($list, 'kefu_id'))->select()->toArray();
            $data = array_column($list, null, 'kefu_id');
            $kefu_ids = array_column($list, 'kefu_id');
            $kefuGroupIds = array_column($kefuList, 'kefu_group_id');
            $kefuGroup = Db::table('su_kefu_group')->where('id', 'in', $kefuGroupIds)->select()->toArray();
            $kefuGroupData = array_column($kefuGroup, null, 'id');
            //获取客服账号个数
            $kefu_account = Db::table('su_kefu_account')->field('kefu_user_id, count(1) as kefuAccountCnt')->where('kefu_user_id', 'in', $kefu_ids)->group('kefu_user_id')->select()->toArray();
            $kefuAccountData = array_column($kefu_account, null, 'kefu_user_id');
            $kefu_account_tmp = Db::table('su_kefu_account')->where('kefu_user_id', 'in', $kefu_ids)->select()->toArray();
            $kefu_account_tmp_data = array_column($kefu_account_tmp, 'kefu_account', 'kefu_user_id');
            foreach ($kefuList as $val) {
                $val['used_num'] = 0;
                $val['contact_num'] = 0;
                $val['kefu_group_name'] = "";
                $val['kefu_account_num'] = 0;
                $val['total_pay'] = 0;
                $val['avg_pay'] = 0;
                $kefuId = $val['id'];
                $kefu_group_id = $val['kefu_group_id'];
                if (isset($data[$kefuId])) {
                    $kefuCntData = $data[$kefuId];
                    $val['used_num'] = $kefuCntData['kefuCnt'];
                    $val['contact_num'] = $kefuCntData['contactCnt'];
                }
                if (isset($kefuGroupData[$kefu_group_id])) {
                    $kefuGroupDataTmp = $kefuGroupData[$kefu_group_id];
                    $val['kefu_group_name'] = $kefuGroupDataTmp['name'];
                }
                if (isset($kefuAccountData[$kefuId])) {
                    $kefuAccountDataTmp = $kefuAccountData[$kefuId];
                    $val['kefu_account_num'] = $kefuAccountDataTmp['kefuAccountCnt'];
                    $val['kefu_account'] = $kefu_account_tmp_data[$kefuId];
                }

                $content[] = $val;
            }

        }
        $this->success("", "", $content);
    }

    //埋点统计
    public function buriedPointStatistics()
    {
        if (!$this->is_admin) {
            $this->success("没有权限访问");
        }
        $data = [
            'browse_num' => 0,
            'register_num' => 0,
            'contact_kefu_num' => 0,
        ];
        if ($this->request->isPost()) {
            $params = $this->request->post();
            $time = isset($params["startTime"]) ? date('Y-m-d', strtotime($params["startTime"])) : date('Y-m-d');
            $endTime = isset($params["endTime"]) ? date('Y-m-d 23:59:59', strtotime($params["endTime"])) : date('Y-m-d 23:59:59');

            $model = new UserInfo();
            $where['create_time'] = ['between', [$time, $endTime]];
            $userInfo = $model->where($where)->field('count(1) as register_num, sum(is_check_kf_switch) as contact_kefu_num')->find();

            if ($userInfo) {
                $data['register_num'] = $userInfo['register_num'];
                $data['contact_kefu_num'] = $userInfo['contact_kefu_num'];
            }

            $gModel = new GuoXueLog();
            $where['type'] = 1;
            $guoXueLogInfo = $gModel->where($where)->field('count(1) as browse_num')->find();

            if ($guoXueLogInfo) {
                $data['browse_num'] = $guoXueLogInfo['browse_num'];
            }
        }

        $this->success('', '', $data);

    }

}